package com.hust.query.dian.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;


import com.hust.query.dian.R;

import java.io.FileNotFoundException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class ActivityUtils {

    public static final int REGISTER_ACTIVITY = 10;

    public static final int REQUEST_CAMERA = 13;

    public static final int REQUEST_ALBUM = 14;

    public static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";

    private static final String TAG = "ActivityUtils";

    public static boolean isTopActivity(Context context, String packageName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            //应用程序位于堆栈的顶层
            if (packageName.equals(tasksInfo.get(0).topActivity.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    public static int randomColor() {
        return Color.argb(127, ((Long) Math.round(Math.random() * 255)).intValue(), ((Long) Math.round(Math.random() * 255)).intValue(), ((Long) Math.round(Math.random() * 255)).intValue());
    }

    /**
     * This method convets dp unit to equivalent device specific value in pixels.
     *
     * @param dp      A value in dp(Device independent pixels) unit. Which we need to convert into pixels
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent Pixels equivalent to dp according to device
     */
    public static float convertDpToPixel(float dp, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return px;
    }

    /**
     * This method converts device specific pixels to device independent pixels.
     *
     * @param px      A value in px (pixels) unit. Which we need to convert into db
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent db equivalent to px value
     */
    public static float convertPixelsToDp(float px, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float dp = px / (metrics.densityDpi / 160f);
        return dp;

    }


    public static int getStatusBarHeight(Activity activity) {
        Rect rect = new Rect();
        Window win = activity.getWindow();
        win.getDecorView().getWindowVisibleDisplayFrame(rect);
        return (int) convertPixelsToDp(rect.top, activity);
    }

    public static String getRealPathFromURI(Uri contentUri, Activity activity) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    public static String getPathFromUri(Uri contentUri) {
        return contentUri.getPath();
    }

    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception", e);
        }
        return versionName;
    }

    /**
     * 窗体跳转
     *
     * @param old
     * @param cls
     */
    public static void jump(Context old, Class<?> cls, int requestCode, Bundle mBundle) {
        jump(old, cls, requestCode, mBundle, false);
    }

    /**
     * 窗体跳转
     *
     * @param old
     * @param cls
     */
    public static void jump(Context old, Class<?> cls, int requestCode, Bundle mBundle, boolean clearTop) {
        Intent intent = new Intent(old, cls);
        if (mBundle == null) {
            mBundle = new Bundle();
        }
        Activity oldActivity = (Activity) old;
        mBundle.putString("from", oldActivity.getClass().getSimpleName());
        intent.putExtras(mBundle);

        Activity activity = (Activity) old;
        if (clearTop) {
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.finish();
        }

        activity.startActivityForResult(intent, requestCode);
    }

    public static void jumpWithNoHistory(Context old, Class<?> cls, int requestCode, Bundle mBundle) {
        Intent intent = new Intent();
        intent.setClass(old, cls);
        if (mBundle != null) {
            intent.putExtras(mBundle);
        }

        Activity activity = (Activity) old;
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        activity.startActivityForResult(intent, requestCode);

    }


    public static void jump(Context old, Class<?> cls, int requestCode) {
        jump(old, cls, requestCode, null);
    }


    public static void back(Context old) {
        back(old, null);
    }

    public static void back(Context old, Bundle mBundle) {
        Activity activity = (Activity) old;
        Intent intent = activity.getIntent();
        if (mBundle != null) {
            intent.putExtras(mBundle);
        }
        activity.setResult(Activity.RESULT_OK, intent);
        activity.finish();
    }

    /**
     * 添加控件(会删除之前layout所有控件)
     *
     * @param layout
     * @param view
     */
    public static void addViewOnly(ViewGroup layout, View view) {
        try {
            if (layout.getChildCount() > 0) {
                layout.removeAllViews();
            }
            layout.addView(view);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void runInUIThread(Context context, final Toast toast) {
        final Activity activity = (Activity) context;
        activity.runOnUiThread(new Runnable() {
            public void run() {
                toast.show();
            }
        });
    }

    public static Display getWindowDisplay(Context context) {
        return ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    }

    public static String getPhoneNumber(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String phoneNumber = telephonyManager.getLine1Number();
        return phoneNumber;
    }

    public static String getDeviceId(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }

    public static String getString(Context context, final int mStringId) {
        return context.getResources().getString(mStringId);
    }

    public static int getColor(Context context, final int mColorId) {
        return context.getResources().getColor(mColorId);
    }

    public static int getPX(Context context, int dipValue) {
        float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, context.getResources().getDisplayMetrics());
        return (int) px;
    }

    public static void showInput(EditText editText) {
        InputMethodManager inputManager =
                (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, 0);
    }

    /**
     * 隐藏软键盘
     */
    public static void hideKeyboard(Activity activity) {
        InputMethodManager m = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (m != null) {
            m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 隐藏软键盘
     */
    public static void showKeyboard(final Activity activity) {
//        InputMethodManager imm = (InputMethodManager) activity.
//                getSystemService(Context.INPUT_METHOD_SERVICE);
//        if (imm != null) {
//            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
//        }

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 500);
    }

    public static boolean isApkAvailable(Context context, String packageName) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(
                    packageName, 0);

        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;
        }
    }

    public static void openApk(Context context, String packageName) {
        if (isApkAvailable(context, packageName)) {
            Intent intent = new Intent();
            intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
            context.startActivity(intent);
        } else {//未安装，跳转至market下载该程序
            Uri uri = Uri.parse("market://details?id=" + packageName);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(it);
        }
    }

    public static Drawable getDrawable(Context context, String mDrawableName) {
        Resources res = context.getResources();
        int resID = res.getIdentifier(mDrawableName, "drawable", context.getPackageName());
        Drawable drawable = res.getDrawable(resID);
        return drawable;
    }


    public static View addListViewHeaderView(ListView listview, int layoutId, Context context) {
        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = mInflater.inflate(layoutId, null);
        listview.addHeaderView(view);
        return view;
    }


    // =========================================================================
    // app版本信息
    // =========================================================================
    public static int getCurrentVersionCode(Context context) {
        PackageInfo pinfo;
        int versionCode;
        try {
            pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionCode = pinfo.versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            versionCode = -1;
            e.printStackTrace();
        }
        return versionCode;
    }

    public static String getCurrentVersionName(Context context) {
        PackageInfo pinfo;
        String versionName = null;
        try {
            pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionName = pinfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 创建快捷方式
     */

    public static void createShortCut(Activity activity, int drawableResourceId) {
        // 创建快捷方式的Intent
        Intent shortcutintent = new Intent(
                "com.android.launcher.action.INSTALL_SHORTCUT");
        ComponentName comp = new ComponentName(activity.getPackageName(),
                activity.getPackageName() + "." + activity.getLocalClassName());
        Intent intent = new Intent(Intent.ACTION_MAIN).setComponent(comp);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                activity.getString(R.string.app_name));
        // 快捷图片
        Parcelable icon = Intent.ShortcutIconResource.fromContext(
                activity.getApplicationContext(), drawableResourceId);
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
        // 点击快捷图片，运行的程序主入口
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        // 发送广播。OK
        activity.sendBroadcast(shortcutintent);
    }

    /**
     * 判断是否在前台
     *
     * @return
     */
    public static boolean isAppOnForeground(Context context) {
        List<RunningTaskInfo> tasksInfo = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            // 应用程序位于堆栈的顶层
            if (context.getPackageName().equals(tasksInfo.get(0).topActivity
                    .getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /*
    * 创建图片来源选择对话框，context传调用的activity
    * */
    public static void createPhotoSelectDialog(final Context context) {
        final String[] PhotoSource = new String[] { "用相机拍照", "从图库中选择" };

        Dialog alertDialog = new AlertDialog.Builder(context).
                setTitle("选择来源")
                .setIcon(R.mipmap.ic_launcher)
                .setItems(PhotoSource, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(context, PhotoSource[which], Toast.LENGTH_SHORT).show();
                        switch (which) {
                            case 0:
                                Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                                ((Activity)context).startActivityForResult(intent, ActivityUtils.REQUEST_CAMERA);
                                break;
                            case 1:
//                                ActivityUtils.jump(context,SQWImageActivity.class, ActivityUtils.REQUEST_ALBUM);
                                break;
                        }
                    }
                }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                            }
                        }).create();
        alertDialog.show();
    }

    /*
    * 将图片的URI作为参数传过去，并设置裁剪后的size，context是activity
    * */
    public static void cropImageUri(Context context, Uri uri, int outputX, int outputY, int requestCode){
        Intent intent = new Intent("com.android.camera.action.CROP");

        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");

        intent.putExtra("aspectX", 2);

        intent.putExtra("aspectY", 1);

        intent.putExtra("outputX", outputX);

        intent.putExtra("outputY", outputY);

        intent.putExtra("scale", true);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        intent.putExtra("return-data", false);

        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        intent.putExtra("noFaceDetection", true); // no face detection

        ((Activity)context).startActivityForResult(intent, requestCode);

    }

    /*
    * 根据Uri解析Bitmap，context可以为activity
    * */
    public static Bitmap decodeUriAsBitmap(Context context, Uri uri){
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }


}
